package controllers.admin

import controllers.{RequestAsJson, checkAdmin}
import play.api.Logging
import play.api.libs.json.{JsArray, JsError, JsValue, Json}
import play.api.mvc.{AbstractController, AnyContent, BodyParsers, Codec, ControllerComponents, Request}
import services.{LayUIRobotTalk, LayUiRobotMsg, OutStockPostParameters}
import services.dingtalk.RobotMessageService

import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class RobotMsgController @Inject()(cc: ControllerComponents, robot: RobotMessageService)(implicit exec: ExecutionContext, parser: BodyParsers.Default)
  extends AbstractController(cc) with play.api.i18n.I18nSupport with RequestAsJson with Logging {
  implicit val myCustomCharset = Codec.javaSupported("gb18030")

  def index(tab: String) = checkAdmin(parser, exec) { implicit request =>
    Ok(views.html.robotmsg.index(tab, robot.talkIdName))
  }

  def robotRouter(api: String) = Action { implicit request =>
    logger.debug(request.body.asText.getOrElse(""))
    request.map(r => logger.debug(r.asText.getOrElse("")))
    logger.debug(request.queryString.toString())
    Ok(api)
  }

  def talk() = checkAdmin.async { implicit request =>
    val req = request.body.asJson.getOrElse(Json.obj("op" -> "", "Key" -> ""))
    logger.debug(request.body.toString())
    try {
      (req \ "op").as[String] match {
        case "create" => Future(Ok("op error"))
        case "update" => Future(Ok("op error"))
        case "delete" => Future(Ok("op error"))
        case "list" => talkList(req)
        case _ => Future(Ok("op error"))
      }

    } catch {
      case exception: Exception =>
        logger.error(s"RobotMsgController.talk request.body:${request.body.toString}", exception);
        Future(Ok("json error"))
    }

  }

  def talkList(request:JsValue) = {
    val p:LayUIRobotTalk = LayUIRobotTalk(
    name = (request \ "name").asOpt[String],
    access = (request \ "access").asOpt[String],
    note = Option(s"""%${(request \ "note").asOpt[String].getOrElse("")}%"""),
    status = (request \ "status").asOpt[String],
    page= (request \ "page").as[Int],
    limit = (request \ "limit").as[Int]
    )
    logger.debug(s"robotTalkList post json is: ${p.toString}")
    val res = robot.talkList(p)
    implicit val tableResJson = Json.format[LayUIRobotTalk]
    res.map { page =>
      val data = page._1.map(i => robot.layuiChange(i))
      Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))

    }
  }

  def talkList1() = checkAdmin(parse.json, exec).async { implicit request =>
    val placeResult = request.body.validate[LayUIRobotTalk]
    logger.debug(placeResult.toString)
    placeResult.fold(
      errors => {
        Future(BadRequest(Json.obj("code" -> 0, "message" -> JsError.toJson(errors), "count" -> 0, "data" -> errors.toString())))
      },
      p => {
        logger.debug(s"robotTalkList post json is: ${p.toString}")
        val res = robot.talkList(p)
        implicit val tableResJson = Json.format[LayUIRobotTalk]
        res.map { page =>
          val data = page._1.map(i => robot.layuiChange(i))
          Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))

        }
      }
    )

  }

  def message() = checkAdmin.async { implicit request =>
    val req = request.body.asJson.getOrElse(Json.obj("op" -> "", "Key" -> ""))
    logger.debug(s"message()=>req.toString():${req.toString()}")
    try {
      req("op").as[String] match {
        case "create" => Future(Ok("op error"))
        case "update" => Future(Ok("op error"))
        case "delete" => {
          try {
            val result = if ((req \ "key").as[String] == "id") {
              val idArr = (req \ "id").as[JsArray].value.toArray
              robot.msgRemove(idArr.map(f => f.as[Long]))
            } else {
              robot.msgRemove(Array())
            }
            result.map { res =>
              Ok(s"delete(${res.length})")
            }
          } catch {
            case e: Exception => {
              Future(Ok("delete error"))
            }
          }
        }
        case "list" => messageList(req)
        case _ => Future(Ok("op error"))
      }

    } catch {
      case exception: Exception =>
        logger.error(s"RobotMsgController.talk request.body:${request.body.toString}", exception);
        Future(Ok("json error"))
    }
  }

  def messageList(request:JsValue) = {
   val p = OutStockPostParameters(
     page = (request \ "page").as[Int],
     limit = (request \ "limit").as[Int],
     sdate = (request \ "sdate").as[String],
     status = (request \ "status").as[String].toInt,
     p1 = (request \ "p1").as[String],
     p2 = (request \ "p2").as[String]
   )
    logger.debug(p.toString)

        logger.debug(s"robotTalkList post json is: ${p.toString}")
        val res = robot.msgList(talkId=p.p2.toLong,title = p.p1, pDateStr = p.sdate, pStatus = p.status, page = p.page, limit = p.limit)
        implicit val tableResJson = Json.format[LayUiRobotMsg]
        res.map { page =>
          val data = page._1.map(i => robot.layuiChange(i))
          Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))
        }


  }


  def messageList1(request:JsValue) = {
    implicit val formDataWrite = Json.reads[OutStockPostParameters]
    val placeResult = request.validate[OutStockPostParameters]
    logger.debug(placeResult.toString)
    placeResult.fold(
      errors => {
        Future(BadRequest(Json.obj("code" -> 0, "message" -> JsError.toJson(errors), "count" -> 0, "data" -> errors.toString())))
      },
      p => {
        logger.debug(s"robotTalkList post json is: ${p.toString}")
        val res = robot.msgList(talkId=p.p2.toLong,title = p.p1, pDateStr = p.sdate, pStatus = p.status, page = p.page, limit = p.limit)
        implicit val tableResJson = Json.format[LayUiRobotMsg]
        res.map { page =>
          val data = page._1.map(i => robot.layuiChange(i))
          Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))
        }
      }
    )
  }

}

